"use server"
import { cookies, headers } from "next/headers"
import Negotiator from "negotiator"
import { match } from "@formatjs/intl-localematcher"
import { Locale, locales, defaultLocale } from "@/i18n/config"

const COOKIE_NAME = "NEXT_LOCALE"

export async function getUserLocale() {
  let languages: string[] | undefined

  // 从 cookie 中获取
  const localeCookie = (await cookies()).get(COOKIE_NAME)
  languages = localeCookie?.value ? [localeCookie.value] : []

  // 从 header 中获取
  if (!languages.length) {
    const acceptLanguage = (await headers()).get("accept-language") || ""
    languages = new Negotiator({ headers: { "accept-language": acceptLanguage } }).languages()
  }

  // 使用默认语言
  if (
    !Array.isArray(languages) ||
    languages.length === 0 ||
    !languages.every((lang) => typeof lang === "string" && /^[\w-]+$/.test(lang))
  ) {
    languages = [defaultLocale]
  }

  return match(languages, locales, defaultLocale)
}

export async function setUserLocale(locale: Locale) {
  const cookieStore = await cookies()
  cookieStore.set(COOKIE_NAME, locale)
}
